package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;


    //新增地址
    @Override
    public void addAddress(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(0);
        addressBookMapper.addAddress(addressBook);
    }

    //查询地址
    @Override
    public List<AddressBook> listAddress() {
        //获取当前用户的ID
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        return addressBookMapper.listAddress(addressBook);
    }


    //根据ID修改地址
    @Override
    public void updateAddress(AddressBook addressBook) {
        addressBookMapper.updateAddress(addressBook);
    }

    //根据ID删除地址
    @Override
    public void deleteAddress(Long id) {
        //获取当前用户的ID
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setId(id);
        addressBookMapper.deleteAddress(addressBook);
    }

    //根据ID查询地址
    @Override
    public AddressBook getAddress(Long id) {

        AddressBook addressBooks = addressBookMapper.getById(id);
        return addressBooks;
    }

    //查询默认地址
    @Override
    public List<AddressBook> defaultAddress() {
        //获取当前用户的ID
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(1);
        return addressBookMapper.listAddress(addressBook);
    }

    //设置默认地址
    @Transactional
    @Override
    public void setDefaultAddress(AddressBook addressBook) {
        //1、将当前用户的所有地址修改为非默认地址 update address_book set is_default = ? where user_id = ?
        addressBook.setIsDefault(0);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.setDefaultAddress(addressBook);

       //2、将当前地址改为默认地址 update address_book set is_default = ? where id = ?
        addressBook.setIsDefault(1);
        addressBookMapper.updateAddress(addressBook);
    }


}
